import { isArray, isObject, YYYY_MM_DD_HH_MM_SS } from '../utils/utils';

import { getLogger } from 'log4js';
import { KoaMiddlewareInterface, Middleware } from 'routing-controllers';
import * as moment from "moment"
const logger = getLogger("access")
@Middleware({ type: "before" })
export class LoggerBeforeMiddleware implements KoaMiddlewareInterface {
    use(context: any, next: (err?: any) => Promise<any>): Promise<any> {
        let { method, url, body } = context.request

        if (method === "GET") {
            logger.info(" <-- " + method + "  " + url)
        } else {
            logger.info(" <-- " + method + "  " + url + "  " + JSON.stringify(body))
        }
        return next()
    }
}

@Middleware({ type: "after" })
export class LoggerMiddleware implements KoaMiddlewareInterface {
    use(context: any, next: (err?: any) => Promise<any>): Promise<any> {
        let { method, url } = context.request
        let { body } = context.response
        if (body?.data) {
            bodyDateFormat(body.data)
        }
        logger.info(" --> " + method + "  " + url + "  " + JSON.stringify(body))

        return next().then((res) => {
            //console.log(res)
        }).catch(err => {
            console.log(err)
        }
        )
    }
}

function bodyDateFormat(data: any) {
    if (isObject(data)) {
        for (let [key, value] of Object.entries(data)) {
            if (key === 'createTime' || key === 'updateTime') {
                data[key] = moment(value).format(YYYY_MM_DD_HH_MM_SS)
            } else if (isObject(value)) {
                bodyDateFormat(value)
            } else if (isArray(value)) {
                (value as []).forEach(obj => {
                    bodyDateFormat(obj)
                })
            }
        }
    } else if (isArray(data)) {
        (data as []).forEach(obj => {
            bodyDateFormat(obj)
        })
    }
}